<?php
include("config.php");
include("multiverse_db.php");
/*if (isset($_POST["args2"])) {
  print_r($_POST["args2"]);
  exit;
}*/
if (isset($_GET["universe"])) {
  // TODO: check for referrer to disable universe to universe modification
  // echo $_SERVER['HTTP_REFERER'];
  $universe = $_GET["universe"];
} else {
  echo "No universe defined";
  exit;
}

global $db;
$db = new multiverse_db(
  $config->mysql_host, 
  $config->mysql_username, 
  $config->mysql_password,
  $config->mysql_database,
  $universe);

try {
  if (isset($_GET["display"])) {
    // main.php?universe=universe&display=being->source->id->1
    list($table, $column, $where_key, $where_value) = explode("->", $_GET["display"]);
    $where = isset($where_key) ? array($where_key => $where_value) : 1;
    $result = $db->$table->select($where, array($column));
    echo $result[$column];
    exit;
  }

  if (isset($_POST["call"])) {
    $call = $_POST["call"];
    if (isset($_POST["args"])) {
      $args = json_decode($_POST["args"], true);
    }
    if (isset($_POST["args2"])) {
      $args2 = json_decode($_POST["args2"], true);
    }
    if ($call == "create_table") {
      $db->create_table($args, $args2);
    } elseif ($call == "drop_table") {
      $db->create_table($args);
    } elseif (strpos($call, "->")) {
      list($table, $function) = explode("->", $call);
      switch ($function) {
        case "select":
          if (isset($args2)) {
            echo json_encode($db->$table->select($args, $args2));
          } else {
            echo json_encode($db->$table->select($args));
          }
          break;
        case "select_all":
          if (isset($args2)) {
            echo json_encode($db->$table->select_all($args, $args2));
          } else {
            echo json_encode($db->$table->select_all($args));
          }
          break;
        case "insert":
          $db->$table->insert($args);
          break;
        case "delete":
          $db->$table->insert($args);
          break;
        case "update":
          $db->$table->update($args, $args2);
          break;
      }
    }
    exit;
  }
} catch (Exception $e) {
  echo $e->getMessage();
  exit;
}

// create the universe from the source of the first being
$result = $db->world->select(1, array("source"));
echo $result["source"];
?>
